<template>
  <div>
    <el-menu
      class="menu-container"
      :background-color="systemInfo.theme"
      :text-color="systemInfo.colorValue"
      :active-text-color="systemInfo.colorValue"
      menu-trigger="hover"
      v-if="systemInfo.topNav === 'leftAndTop'"
      :default-active="activeMenu"
      mode="horizontal"
      @select="handleSelect"
    >
      <template v-for="(item, index) in topMenus">
        <el-menu-item
          :index="item.fullPath"
          :key="index"
          :data-test="`menu-li-${item.meta.title}`"
          v-if="index < visibleNumber && item.meta"
        >
          {{ item.meta.title }}
        </el-menu-item>
      </template>

      <!-- 顶部菜单超出数量折叠 -->
      <el-submenu
        index="more"
        v-if="topMenus.length > visibleNumber"
        class="sub-menu-more"
        popper-class="sub-menu-more-list"
      >
        <template slot="title">
          <div class="menu-more-container">
            <i
              class="iconfont icon-more-horizontal"
              :style="{ color: systemInfo.colorValue }"
            ></i>
          </div>
        </template>
        <template v-for="(item, index) in topMenus">
          <el-menu-item
            :class="[
              'sub-menu-more-list-item',
              activeMenu === item.fullPath ? 'more-item-active' : '',
            ]"
            :index="item.fullPath"
            :key="item.fullPath"
            v-if="index >= visibleNumber"
          >
            {{ item.meta.title }}
          </el-menu-item>
        </template>
      </el-submenu>
    </el-menu>

    <el-menu
      class="menu-container top-menu-container"
      :background-color="systemInfo.theme"
      :text-color="systemInfo.colorValue"
      :active-text-color="systemInfo.colorValue"
      v-if="systemInfo.topNav === 'top'"
      :default-active="activeMenu2"
      mode="horizontal"
    >
      <template v-for="(route, index) in topMenus">
        <top-nav-item
          v-if="index < visibleNumber && route.meta"
          :key="route.path"
          :item="route"
        />
      </template>

      <el-submenu
        index="more"
        v-if="topMenus.length >= visibleNumber"
        class="sub-menu-more"
      >
        <template slot="title">
          <div class="menu-more-container">
            <i
              class="iconfont icon-more-horizontal"
              :style="{ color: systemInfo.colorValue }"
            ></i>
          </div>
        </template>
        <template v-for="route in topMenus.slice(visibleNumber)">
          <top-nav-item :key="route.path" :item="route" />
        </template>
      </el-submenu>
    </el-menu>
  </div>
</template>

<script>
import { mapState, mapGetters } from "vuex";

import TopNavItem from "./TopNavItem";

export default {
  components: { TopNavItem },
  data() {
    return {
      // 顶部栏初始数
      visibleNumber: null,
      // 是否为首次加载
      isFrist: false,
      // 当前激活菜单的 index
      currentIndex: undefined,
    };
  },
  computed: {
    ...mapState(["settings"]),
    ...mapGetters(["sidebarRouters", "systemInfo"]),
    activeMenu2() {
      return this.$route.path;
    },
    // 顶部显示菜单
    topMenus() {
      let topMenus = [];
      this.routers.map((menu) => {
        if (menu.hidden !== true) {
          // 兼容顶部栏一级菜单内部跳转
          if (menu.path === "/") {
            topMenus.push(menu.children[0]);
          } else {
            topMenus.push(menu);
          }
        }
      });
      return topMenus;
    },
    // 所有的路由信息
    routers() {
      return this.$store.state.permission.routes;
    },
    // 默认激活的菜单
    activeMenu() {
      const path = this.$route.path;

      const router = this.routers;
      let activePath = router[0].path;
      if (path.lastIndexOf("/") > 0) {
        const tmpPath = path.substring(1, path.length);
        activePath = "/" + tmpPath.substring(0, tmpPath.indexOf("/"));
        const menu = router.find((item) => {
          if (item.path == activePath) {
            return item;
          }
        });
        if (menu) {
          if (
            (!menu.children || menu.children.length == 1) &&
            (!menu.children[0].children ||
              menu.children[0].children.length == 1) &&
            this.systemInfo.topNav === "leftAndTop"
          ) {
            // 判断 若不是隐藏菜单，在隐藏左边导航
            if (!menu.children[0].hidden) {
              this.sidebarShow(false);
            } else {
              this.$store.commit("SET_SIDEBAR_ROUTERS", []);
              this.sidebarShow(true);
            }

            return menu.path;
          } else {
            this.sidebarShow(true);
          }
        } else {
          this.sidebarShow(true);
        }
      } else if ("/index" == path || "" == path) {
        if (!this.isFrist) {
          this.isFrist = true;
        } else {
          activePath = "index";
        }
        this.sidebarShow(true);
      }
      var routes = this.activeRoutes(activePath);
      if (routes && routes.length === 0) {
        activePath = this.currentIndex || this.routers[0].path;
        this.activeRoutes(activePath);
      }
      return activePath;
    },
  },
  beforeMount() {
    window.addEventListener("resize", this.setVisibleNumber);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.setVisibleNumber);
  },
  mounted() {
    this.setVisibleNumber();
  },
  created() {
    this.visibleNumber = this.routers.length;
  },
  methods: {
    // 根据宽度计算设置显示栏数
    setVisibleNumber() {
      const selfAdapt =
        document.getElementsByClassName("project-info-wrap")[0].clientWidth;
      const totalWidth = document.body.getBoundingClientRect().width;
      const width =
        sp_config.LAYOUT_TYPE === 2
          ? totalWidth
          : this.systemInfo.isSelfAdapt
          ? totalWidth - selfAdapt - 355
          : totalWidth - 565;
      this.visibleNumber = parseInt(width / 125) - 1;
    },
    // 菜单选择事件
    handleSelect(key, keyPath) {
      this.currentIndex = key;
      let menu = this.topMenus.find((item) => item.path === key);
      if (!menu.children || menu.children.length === 1) {
        let parentPath = menu.path,
          currentPath = menu.children[0].path;
        let path = `${parentPath}/${currentPath}`;
        if (currentPath.indexOf(parentPath) !== -1) path = currentPath;
        if (this.$route.path !== path) this.$router.push({ path: path });
      } else {
        if (this.isHttp(key)) {
          // http(s):// 路径新窗口打开
          window.open(key, "_blank");
        } else if (key.indexOf("/redirect") !== -1) {
          // /redirect 路径内部打开
          this.$router.push({ path: key.replace("/redirect", "") });
        } else {
          // 显示左侧联动菜单
          this.activeRoutes(key);
          this.$router.push({ path: menu.path });
        }
      }
    },
    /**
     * 左侧导航是否显示
     */
    sidebarShow(flag) {
      this.$store.dispatch("settings/changeSetting", {
        key: "sidebarShow",
        value: flag,
      });
    },
    // 当前激活的路由
    activeRoutes(key) {
      let routes = this.routers.find((r) => r.path === key);
      if (this.systemInfo.topNav === "leftAndTop") {
        if (routes && routes.children && routes.children instanceof Array) {
          this.$store.commit("SET_SIDEBAR_ROUTERS", routes.children);
        } else {
          this.$store.commit("SET_SIDEBAR_ROUTERS", []);
        }
      }
      return routes;
    },
    isHttp(url) {
      return url.indexOf("http://") !== -1 || url.indexOf("https://") !== -1;
    },
  },
};
</script>

<style lang="scss" scoped>
.menu-container {
  ::v-deep .el-menu-item {
    font-size: 15px;
    height: 60px;
    line-height: 60px;
    color: #fff;
    padding: 0 18px;
    margin: 0 12px;
  }
  ::v-deep .el-menu-item.is-active {
    // background: $menuHoverColor !important; //主题开放后删除
    // color: #fff !important;
    // border-bottom: 2px solid #1890ff !important; //主题开放后删除
  }

  .sub-menu-more {
    height: 60px;
    width: 120px;

    ::v-deep .el-submenu__title {
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-bottom-color: transparent !important;

      .el-submenu__icon-arrow {
        display: none;
      }

      .menu-more-container {
        height: 60px;
        line-height: 60px;

        i {
          // color: #fff !important;
          font-size: 24px;
        }
      }
    }
  }

  // .is-active {  //主题开放后删除
  //   ::v-deep > .el-submenu__title {
  //     background: #115ea4 !important;
  //     color: #fff !important;
  //     border-bottom: 2px solid #1890ff !important;
  //   }
  // }
  ::v-deep .el-submenu__title {
    height: 60px !important;
    line-height: 60px !important;
    font-size: 15px;
  }
}

.top-menu-container {
  ::v-deep .el-menu--popup .sub-menu-more-list-item2.is-active {
    border-bottom: 0 !important;
  }
}
</style>

<style lang="scss" scoped>
.sub-menu-more-list {
  width: 120px;
  overflow: hidden;

  .sub-menu-more-list-item {
    width: 100%;
    max-width: 200px;
    padding-left: 18px !important;
  }

  // .more-item-active { //主题开放后删除
  //   background-color: rgb(18, 95, 165) !important;
  // }
}
::v-deep .el-menu.el-menu--horizontal {
  border-bottom: 0 !important;
}
</style>
